<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
/**
 * 商品
 *
 * @author chaituan@126.com
 */
class Goods extends AdminCommon {
	function __construct() {
		parent::__construct();
		$this->load->model(array('admin/Goods_model'=>'do','admin/Goods_cat_model'=>'do_cat'));
	}
	
	public function index() {
		$this->load->view ('admin/goods/index');
	}
	
	function lists(){
		$name = Gets('name');
		$page = Gets('page','checkid');$limit = Gets('limit','checkid');
		$total = Gets('total','num');
		$where = $name?"names like '%$name%'":'';
		$data = $this->do->getItems($where,'','id desc',$page,$limit,$total);
		$find = Gets('find');
		if(($name&&$find)||!$total){
			$total = $this->do->count;
		}
		f_ajax_lists($total, $data);
	}
	
	public function add() {
		if (is_ajax_request ()) {
			$data = Posts('data');
			$data['addtime'] = time();
			if ($this->do->add ( $data )) {
				AjaxResult_ok ();
			} else {
				AjaxResult_error ();
			}
		} else {
			$items = $this->do_cat->get_catcachetree ();
			$data ['parent'] = $items;
			$this->load->view('admin/goods/add',$data);
		}
	}
	public function edit() {
		if (is_ajax_request ()) {
			$data = Posts('data');
			$sku = json_decode($data['sku_paths'],true);
			if($sku){
				foreach ($sku as $k=>$v){
					$sku_titles = $v['titles'];
					$sku_options = $v['s_options'];
					$sku_price[$k] = $v['price'];
					$sku_stock[$k] = $v['stock'];
				}
				$data['sku_titles'] = json_encode($sku_titles,JSON_UNESCAPED_UNICODE );
				$data['sku_options'] = json_encode($sku_options,JSON_UNESCAPED_UNICODE );
				$data['sku_price'] = json_encode($sku_price,JSON_UNESCAPED_UNICODE );
				$data['sku_stock'] = json_encode($sku_stock,JSON_UNESCAPED_UNICODE );
				$data['sku_paths'] = json_encode($sku,JSON_UNESCAPED_UNICODE);
			}else{
				unset($data['sku_paths']);
			}
			
			if ($this->do->updates($data,"id=".Posts('id','checkid'))){
				AjaxResult_ok ();
			}else{
				AjaxResult_error ();
			}
		}else{
			$data ['item'] = $this->do->getItem(array('id' => Gets( 'id', 'checkid' )));
			$items = $this->do_cat->get_catcachetree ();
			$data ['parent'] = $items;
			$this->load->view('admin/goods/edit', $data);
		}
	}
	public function del() {
		$r = $this->do->deletes ( "id=" . Gets ( 'id', 'checkid' ) );
		if ($r) {
			AjaxResult_ok ();
		} else {
			AjaxResult_error ();
		}
	}
	function dels(){
		AjaxResult_error('不支持批量删除');
	}
	function order_by() {
		$data = Posts ( 'data' );
		if (! $data) {
			AjaxResult ( '2', '不能为空' );
		}
		foreach($data as $k=>$v) {
			$datas[] = array ('id' => $k,'sort' => $v);
		}
		$result = $this->do->update_batchs ( $datas, 'id' );
		if ($result) {
			
			AjaxResult_ok ();
		} else {
			AjaxResult_error ();
		}
	}
}
